<?php
session_start();
//set_error_handler('errorHandler');
error_reporting(E_ALL ^ E_NOTICE);

//verify define.php and includea it
file_exists('define.php') ? require_once('define.php') :  die('Please create <b>define.php</b> with your site configuration.');

require_once('component/login/tableLogin.php');
require_once('component/section/tableSection.php');
require_once('component/news/tableNews.php');
require_once('component/gallery/tableGallery.php');
require_once(LIBPATH.'php-html-generator.php');

global $page;
$page       = new page(TITLE);
$page       ->inner['head']->inner['meta']->content = "'text/html; charset='".CHARSET."'";
file_exists('theme/'.THEME.'/index.css') ?  $page->addCss('theme/'.THEME.'/index.css') : die('Cannot find theme <b>'. THEME .'</b> please set a valid one in <b>define.php</b>.');
$page       ->addScript(LIBPATH.'js/genericDrag.js');
$page       ->addScript(LIBPATH.'fckeditor.js');
$page       ->addScript(LIBPATH.'js/fieldValidator.js');
$page       ->addScript(LIBPATH.'js/php-html-generator.js');
$page       ->addScript(LIBPATH.'js/prototype.js');
$page->addAttribute('onkeydown', 'return keyDown(event);');
$page->inner['body']->addAttribute('id','body');

DEFINEJS('GALLERYPATH');
DEFINEJS('THEME');
DEFINEJS('TITLE');

global      $news;
global      $photo;
global      $sections;
global      $db;
try
{
    $db = new PDO(BASESTRING,BASEUSER, BASEPASWD);
}
catch (Exception $e)
{
  die("Can't connect to <b>database</b>.");
}

$login      = new tableLogin();
$news       = new tableNews();
$photo      = new tableGallery();
$sections   = new tableSection();

global $login;

//logoff
if ($_REQUEST['exit'] != null)
{
    $login->connect('','') ;
}

//detecta modo do site (clicado no botão)
if ( is_array($_REQUEST['section'] ) )
{
    foreach ( $_REQUEST['section'] as $line => $info )
    {
        $section = $line;
    }
}
else
{
    $section = $_REQUEST['section'];
}

//se não tiver pega da sessão ( no caso de voltar do admin)
if ( !$section )
{
    $section = $_SESSION['sectionId'];
}

// se ainda não tiver define o padrão ou se tiver busca por title no REQUEST
if ( !$section || $_REQUEST['title'] )
{
    $section = 'news';
}

//grava na sessão para usar após
$_SESSION['sectionId'] = $section;

getAdminInclude();

function login( $args )
{
	global $login;

	$msg = '';

	if ( $_REQUEST['login'] && $_REQUEST['passwd'] )
	{
	    $login->connect($_REQUEST['login'], $_REQUEST['passwd']);

	    if ($login->isLogged() == false )
	    {
	        $msg = 'Usuário ou senha inválidos';
	    }
	    else
	    {
	    	$menu = getAdminMenu();
	    }
	}
	else
	{
        $msg = 'Por favor preencha os dados corretamente.';
	}

	if ( $menu )
	{
		return $menu;
	}

	return new Script( "alert('$msg');" );
}

if ( !$login->isLogged() )
{
    $sectionData = $sections->getSection($section);

    $component   = $sectionData['component'] ? $sectionData['component'] : $section; //se não tem componente setado tenta com o id da seção

    $sectionArgs = explode(';', $sectionData['args']);

    $args = array();

    //monta array de argumentos para passar para o objeto
    if ( is_array ($sectionArgs) )
    {
        foreach ( $sectionArgs as $line => $info )
        {
            $temp = explode('=', $info);
            $args[$temp[0]] = $temp[1];
        }
    }

    $componentFile = 'component/'.$component.'/'.$component.'.php';

    if ( file_exists($componentFile) )
    {
        if ( require_once($componentFile) )
        {
            $newsFields = new $component($args);
        }
    }
    else
    {
        die('Can\'t find component <b>'.$component.'</b>.');
    }

    $theme = getThemeContent('index.html');

    $theme = str_replace('$sessionContent', $newsFields->__toString(), $theme);

    $fields[]  = $theme;
}
else
{
	$fields[] = getAdminMenu();
}

function getAdminInclude()
{
    $function  = $_REQUEST['phpFunction'];
    $temp      = explode(':', $function);
    $function  = $temp[count($temp)-1];
    $class     = $temp[count($temp)-2];

    if ( $class )
    {
        $folder = strtolower(str_replace('admin','', $class));
        require_once("component/$folder/$class.php");
    }
}

function getAdminMenu()
{
	global $login;

    if ( $login->getClass() == 'admin' )
    {
        global $page;

        $page->addScript(LIBPATH.'/js/prototype.js'); //add ajax suport

        //list directories in component folder
        $components = glob('component/*', GLOB_ONLYDIR);

        foreach ( $components as $line => $info)
        {
            //verifies if it has an php script with admin in it.
            $glob = glob( $info.'/admin*.php');
            $glob = $glob[0];

            //if ok make the button in admin area
            if (  $glob )
            {
                $component= str_replace( 'component/', '', $info);
                $component = ucfirst($component);
                $headerButtons[$line] = new Button( $component.'Submit',$component, "ajax('divContent','admin{$component}:__construct')", 'columnTitle');
            }
        }

        //add exit button
        $headerButtons['exit'] = new submit("exit", "Exit", 'columnTitle');
        $headerButtons['exit']-> onClick('SubmitMenuOnClick', 'exit');

        $fields[]  = new div('divSubmits', $headerButtons);
        $fields[]  = new div('divContent', null);
    }

    return $fields;
}

$page->addContent( $fields );
echo $page;
?>